package org.transmit;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 
 * <p>Title: ActionContext   </p>
 * <p>Description: 全局调用  获得session  通过 ThreadLocal 线性安全.</p>
 * <p>Copyright: Copyright (c) 2012</p>
 * <p>Company: prd</p>
 * <p>Create Date/Time: 2014年8月13日 下午9:13:55<p>
 * @author porridge
 * @version 1.0
 * @url www.prdblog.com
 *
 */
public class ActionContext{
	
	private static ThreadLocal<HttpObject> thres=new ThreadLocal<HttpObject>();
	
	protected static void removeThread(){
		thres.remove();
	}
	protected static void setHttpObject(HttpObject obj){
		thres.set(obj);
	}
	/**
	 * 获得对象的集合
	 * @return
	 */
	public static HttpObject getHttpObject(){
		return thres.get();
	}
	/**
	 * 获得request对象
	 * @return
	 */
	public static HttpServletRequest getRequest(){
		return thres.get().getRequest();
	}
	/**
	 * 跳转地址
	 * @param path
	 */
	public static void gotoPath(String path){
		try {
			HttpServletRequest req=getRequest();
			HttpServletResponse resp=getResponse();
			req.getRequestDispatcher(path).forward(req,resp);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获得response对象
	 * @return
	 */
	public static HttpServletResponse getResponse(){
		return thres.get().getResponse();
	}
	/**
	 * 获得session作用域
	 * @return
	 */
	public static HttpSession getSession(){
		return thres.get().getSession();
	}
	/**
	 * 获得application对象
	 * @return
	 */
	public static ServletContext getApplication(){
		return thres.get().getApplication();
	}
	/**
	 * 获得打印对象
	 * @return
	 */
	public static PrintWriter getPrintWriter(){
		HttpServletResponse response=getResponse();
		PrintWriter out=null;
		try {
			out=response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out;
	}
}
